package org.Lin.server;

import org.Lin.util.AESUtil;
import org.Lin.util.DatabaseUtil;
import org.Lin.util.LogUtil;
import org.json.JSONObject;
import java.sql.*;

public class FriendMessageServer {

    public static void handle(JSONObject json) {
        int senderId = json.getInt("sender_id");
        int receiverId = json.getInt("receiver_id");
        String messageData = json.getString("message_data");

        try (Connection conn = DatabaseUtil.getConnection()) {
            String insertSql = "INSERT INTO FriendMessage(sender_id, receiver_id, message_data) VALUES (?, ?, ?)";
            PreparedStatement stmt = conn.prepareStatement(insertSql);
            stmt.setInt(1, senderId);
            stmt.setInt(2, receiverId);
            stmt.setString(3, messageData);
            stmt.executeUpdate();

            JSONObject response = new JSONObject();
            response.put("type", "friend_message_received");
            response.put("status", "success");
            NetworkServer.send(AESUtil.encrypt(response.toString()));

            LogUtil.logOperation("FriendMessage", "send", "发送私聊消息给 " + receiverId + ": " + messageData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
